package com.yz.jdd.module.login.view;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.AuthTask;
import com.yz.jdd.R;
import com.yz.jdd.base.activity.BaseActivity;
import com.yz.jdd.base.entity.Response_Base;
import com.yz.jdd.base.utils.AppUtils;
import com.yz.jdd.base.utils.AuthResult;
import com.yz.jdd.base.utils.BaseConfigs;
import com.yz.jdd.base.utils.Constants;
import com.yz.jdd.base.utils.EditTextUtils;
import com.yz.jdd.base.utils.PreferencesUtils;
import com.yz.jdd.module.bind.view.BindAccountActivity;
import com.yz.jdd.module.launch.view.LaunchActivity;
import com.yz.jdd.module.login.presenter.LoginPresenter;
import com.yz.jdd.module.main.MainActivity;
import com.yz.jdd.module.psd.view.ForgetPsdActivity;
import com.yz.jdd.module.reg.view.RegistActivity;
import com.yz.jdd.network.MySubscriber;
import com.yz.jdd.network.NetWorkRequset;
import com.yz.jdd.network.request.Request_UserLogin;
import com.yz.jdd.webview.download.H5DownFileUtils;

import java.util.Arrays;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by cc on 2017/5/12.
 */

public class LoginActivity extends BaseActivity implements LoginView {

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;

    @BindView(R.id.fill)
    ImageView fill;
    @BindView(R.id.top_back)
    ImageView topBack;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.top_right)
    TextView topRight;
    @BindView(R.id.username)
    EditText username;
    @BindView(R.id.password)
    EditText password;
    @BindView(R.id.forgetpass)
    TextView forgetpass;
    @BindView(R.id.tv_register)//注册
            TextView tv_register;
    @BindView(R.id.login)
    Button login;
    @BindView(R.id.base_view)
    LinearLayout baseView;

    @BindView(R.id.alipay_login)
    ImageView alipay_login;
    LoginPresenter presenter;

    String aliUserId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        finish = false;
//        EnvUtils.setEnv(EnvUtils.EnvEnum.SANDBOX);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        PreferencesUtils.putString(this, BaseConfigs.PREF_ROLE_ID, "");
        PreferencesUtils.putString(this, BaseConfigs.PREF_ROLE_TIME, "");
        PreferencesUtils.putString(this, BaseConfigs.PREF_SHOPID, "");
        presenter = new LoginPresenter(this);
        ButterKnife.bind(this);
        topTitle.setText("登录");
        if (LaunchActivity.instance != null) {
            LaunchActivity.instance.finish();
            LaunchActivity.instance = null;
        }
        Intent intent = getIntent();
        if (intent != null) {
            String logout = intent.getStringExtra("logout");
            if (!TextUtils.isEmpty(logout) && "1".equals(logout)) {
                if (MainActivity.mainActivityObj != null) {
                    MainActivity.mainActivityObj.finish();
                }
            }
        }
        EditTextUtils.inputTextCheck(login, Arrays.<TextView>asList(username,password));
    }

    @OnClick({R.id.forgetpass, R.id.login, R.id.top_back, R.id.alipay_login, R.id.tv_register,R.id.fill})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fill:
                password.setText("");
                break;
            case R.id.forgetpass:
                Intent intent = new Intent(this, ForgetPsdActivity.class);
//                intent.putExtra("action", "forget");
                //这里如果有手机号，就传入下一个页面
                intent.putExtra("tel_no", getUserName());
                startActivity(intent);
                break;
            case R.id.login:
                presenter.userLogin();
//                Intent intent1 = new Intent(this, MainActivity.class);
//
//                startActivity(intent1);
                break;
            case R.id.top_back:
                finish();

                break;
            case R.id.alipay_login:
                getSign();
                break;
            case R.id.tv_register:
                RegistActivity.invoke(this, "");
                break;
        }
    }

    @Override
    public String getUserName() {
        return username.getText().toString().trim();
    }

    @Override
    public String getPassWord() {
        return password.getText().toString().trim();
    }

    @Override
    public String getNetWorkType() {
        return AppUtils.getNetWorkType(this);
    }

    @Override
    public String getLon() {
        return PreferencesUtils.getString(this, BaseConfigs.STRING_LON,
                "0");
    }

    @Override
    public String getLat() {
        return PreferencesUtils.getString(this, BaseConfigs.STRING_LAT,
                "0");
    }

    @Override
    public void startMainActivity() {
//        Intent intent = new Intent(this, H5BridgeActivity.class);
        Intent intent = new Intent(this, MainActivity.class);
        String main_url = "file://" + H5DownFileUtils._UPZIP_FOLDERPATH + "vuepages/index.html#/?s=" +
                PreferencesUtils.getString(this, BaseConfigs.PREF_SESSIONID) +
                "&statusBarHeight=0&android=4.1" + "&SDK=" + Build.VERSION.SDK_INT
                + "&url=" + PreferencesUtils.getString(LoginActivity.this, BaseConfigs.STRING_SERVER_URL, Constants.SERVER_URL);
        intent.putExtra(Constants.H5_WEB_URL, main_url);

        startActivity(intent);

    }

    @Override
    public void close() {
        finish();
    }

    @Override
    public void startBindAccountActivity() {

        if (!TextUtils.isEmpty(aliUserId)) {
            Intent intent = new Intent(this, BindAccountActivity.class);
            intent.putExtra("aliUserId", aliUserId);
            startActivity(intent);
        }

    }

    @Override
    public void startMagicLogin(Request_UserLogin request_userLogin) {
        Intent intent = new Intent(this, LoginActvity.class);
        intent.putExtra("request", request_userLogin);
        startActivity(intent);
        finish();
    }


    /**
     * 获取sign 并且支付宝登录
     */
    public void getSign() {
        showLoading("正在加载...");
        NetWorkRequset.doJoinLogin(new MySubscriber() {
            @Override
            public void onSuccess(Response_Base response_baseModel) {
                dismissLoading();
                String sign = (String) response_baseModel.getResultObject();
                if (!TextUtils.isEmpty(sign)) {
                    authV2(sign);
                } else {
                    showToast("未获取到sign");
                }
            }

            @Override
            public void onNeedLogin(String msg) {
                dismissLoading();

            }

            @Override
            public void onCompleted() {
                super.onCompleted();
                dismissLoading();

            }

            @Override
            public void onFail(Response_Base response_baseModel) {
                dismissLoading();
                if (!TextUtils.isEmpty(response_baseModel.getMsg())) {
                    showToast(response_baseModel.getMsg());
                }
            }
        });
    }


    /**
     * 支付宝账户授权业务
     */
    public void authV2(final String sign) {
        Runnable authRunnable = new Runnable() {

            @Override
            public void run() {
                // 构造AuthTask 对象
                AuthTask authTask = new AuthTask(LoginActivity.this);
                // 调用授权接口，获取授权结果
                Map<String, String> result = authTask.authV2(sign, true);

                Message msg = new Message();
                msg.what = SDK_AUTH_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread authThread = new Thread(authRunnable);
        authThread.start();
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {

                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "9000") && TextUtils.equals(authResult.getResultCode(), "200")) {
                        aliUserId = authResult.getUserId();
                        presenter.alipayLogin(authResult.getUserId());
                    } else {
                        // 其他状态值则为授权失败
                        Toast.makeText(LoginActivity.this, "授权失败", Toast.LENGTH_SHORT).show();

                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

}
